package com.zhentao.device.service;

import com.zhentao.device.websocket.AlertWebSocketHandler;
import com.zhentao.device.service.WaterQualityAnomalyService;
import com.zhentao.pojo.WaterQualityAnomaly;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 告警服务类
 * 负责告警数据的生成、管理和WebSocket推送
 */
@Service
public class AlertService {

    @Autowired
    private WaterQualityAnomalyService waterQualityAnomalyService;

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private final Map<String, AlertData> alerts = new ConcurrentHashMap<>();
    private final Random random = new Random();

    /**
     * 告警数据类
     */
    public static class AlertData {
        private String alertId;
        private String title;
        private String description;
        private String device;
        private String deviceId;
        private String indicator;
        private double currentValue;
        private String normalRange;
        private String severity;
        private int status; // 1-未处理, 2-已确认, 3-已处理
        private String createTime;
        private String handlerId;
        private String handleTime;

        // 构造函数
        public AlertData() {
        }

        public AlertData(String alertId, String title, String description, String device,
                         String deviceId, String indicator, double currentValue,
                         String normalRange, String severity) {
            this.alertId = alertId;
            this.title = title;
            this.description = description;
            this.device = device;
            this.deviceId = deviceId;
            this.indicator = indicator;
            this.currentValue = currentValue;
            this.normalRange = normalRange;
            this.severity = severity;
            this.status = 1; // 默认未处理
            this.createTime = LocalDateTime.now().format(FORMATTER);
        }

        // Getters and Setters
        public String getAlertId() {
            return alertId;
        }

        public void setAlertId(String alertId) {
            this.alertId = alertId;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getDevice() {
            return device;
        }

        public void setDevice(String device) {
            this.device = device;
        }

        public String getDeviceId() {
            return deviceId;
        }

        public void setDeviceId(String deviceId) {
            this.deviceId = deviceId;
        }

        public String getIndicator() {
            return indicator;
        }

        public void setIndicator(String indicator) {
            this.indicator = indicator;
        }

        public double getCurrentValue() {
            return currentValue;
        }

        public void setCurrentValue(double currentValue) {
            this.currentValue = currentValue;
        }

        public String getNormalRange() {
            return normalRange;
        }

        public void setNormalRange(String normalRange) {
            this.normalRange = normalRange;
        }

        public String getSeverity() {
            return severity;
        }

        public void setSeverity(String severity) {
            this.severity = severity;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public String getCreateTime() {
            return createTime;
        }

        public void setCreateTime(String createTime) {
            this.createTime = createTime;
        }

        public String getHandlerId() {
            return handlerId;
        }

        public void setHandlerId(String handlerId) {
            this.handlerId = handlerId;
        }

        public String getHandleTime() {
            return handleTime;
        }

        public void setHandleTime(String handleTime) {
            this.handleTime = handleTime;
        }
    }

    /**
     * 生成新告警
     */
    public void generateAlert(String indicator, double currentValue, String normalRange,
                              String deviceId, String deviceName) {
        try {
            // 使用现有的WaterQualityAnomaly服务生成告警
            waterQualityAnomalyService.generateAlert(indicator, currentValue, normalRange,
                    deviceId, deviceName, 0L);

            // 获取最新生成的告警ID（这里需要从数据库查询最新的一条）
            List<WaterQualityAnomaly> recentAlerts = waterQualityAnomalyService.list();
            if (!recentAlerts.isEmpty()) {
                WaterQualityAnomaly latestAlert = recentAlerts.get(recentAlerts.size() - 1);
                String alertId = latestAlert.getAnomalyId().toString();

                // 通过WebSocket广播新告警
                AlertWebSocketHandler.broadcastNewAlert(latestAlert);

                System.out.println("✅ 生成新告警: " + alertId + " - " + latestAlert.getIndicatorCode() + "异常");
            }

        } catch (Exception e) {
            System.err.println("❌ 生成告警失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 更新告警状态
     */
    public boolean updateAlertStatus(String alertId, int status, String handlerId) {
        try {
            // 使用WaterQualityAnomaly服务更新状态
            boolean success = waterQualityAnomalyService.updateAlertStatus(Long.valueOf(alertId), status, handlerId);

            if (success) {
                // 通过WebSocket广播状态更新
                AlertWebSocketHandler.broadcastAlertUpdate(Long.valueOf(alertId), status, handlerId);
                System.out.println("✅ 更新告警状态: " + alertId + " -> " + status);
            }

            return success;
        } catch (Exception e) {
            System.err.println("❌ 更新告警状态失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除告警
     */

    /**
     * 获取所有告警
     */
    public List<AlertData> getAllAlerts() {
        // 优先从数据库加载数据
        List<AlertData> dbAlerts = loadAlertsFromDatabase();
        if (!dbAlerts.isEmpty()) {
            // 更新内存缓存
            alerts.clear();
            for (AlertData alert : dbAlerts) {
                alerts.put(alert.getAlertId(), alert);
            }
            return dbAlerts;
        }

        // 如果数据库为空，返回内存中的数据
        return new ArrayList<>(alerts.values());
    }

    /**
     * 根据状态获取告警
     */
    public List<AlertData> getAlertsByStatus(int status) {
        return alerts.values().stream()
                .filter(alert -> alert.getStatus() == status)
                .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
    }

    /**
     * 获取告警统计
     */
    public Map<String, Integer> getAlertStats() {
        Map<String, Integer> stats = new HashMap<>();
        stats.put("total", alerts.size());
        stats.put("unhandled", 0);
        stats.put("confirmed", 0);
        stats.put("handled", 0);

        for (AlertData alert : alerts.values()) {
            switch (alert.getStatus()) {
                case 1:
                    stats.put("unhandled", stats.get("unhandled") + 1);
                    break;
                case 2:
                    stats.put("confirmed", stats.get("confirmed") + 1);
                    break;
                case 3:
                    stats.put("handled", stats.get("handled") + 1);
                    break;
            }
        }
        return stats;
    }

    /**
     * 根据严重程度确定告警级别
     */
    private String determineSeverity(String indicator, double currentValue, String normalRange) {
        // 解析正常范围
        String[] range = normalRange.split("-");
        if (range.length != 2) return "medium";

        try {
            double min = Double.parseDouble(range[0]);
            double max = Double.parseDouble(range[1]);
            double deviation = Math.min(Math.abs(currentValue - min), Math.abs(currentValue - max));
            double rangeSize = max - min;
            double deviationPercent = deviation / rangeSize;

            if (deviationPercent > 0.5) return "high";
            if (deviationPercent > 0.2) return "medium";
            return "low";
        } catch (NumberFormatException e) {
            return "medium";
        }
    }

    /**
     * 将数字严重程度转换为文本
     */
    private String getSeverityText(Integer severity) {
        if (severity == null) return "medium";
        switch (severity) {
            case 1:
                return "low";
            case 2:
                return "medium";
            case 3:
                return "high";
            default:
                return "medium";
        }
    }

    /**
     * 保存告警到数据库
     */

    /**
     * 从数据库加载告警数据
     */
    public List<AlertData> loadAlertsFromDatabase() {
        try {
            List<WaterQualityAnomaly> dbAlerts = waterQualityAnomalyService.list();
            List<AlertData> alertDataList = new ArrayList<>();

            for (WaterQualityAnomaly alert : dbAlerts) {
                AlertData alertData = new AlertData();
                alertData.setAlertId(alert.getAnomalyId().toString());
                alertData.setTitle(alert.getIndicatorCode() + "异常"); // 使用指标代码生成标题
                alertData.setDescription(alert.getIndicatorCode() + "值 " + alert.getCurrentValue() + " 超出正常范围 " + alert.getNormalRange()); // 生成描述
                alertData.setDevice("监测点" + alert.getDeviceId()); // 使用设备ID生成设备名称
                alertData.setDeviceId(alert.getDeviceId().toString());
                alertData.setIndicator(alert.getIndicatorCode());
                alertData.setCurrentValue(alert.getCurrentValue().doubleValue());
                alertData.setNormalRange(alert.getNormalRange());
                alertData.setSeverity(getSeverityText(alert.getSeverity()));
                alertData.setStatus(alert.getHandleStatus());
                alertData.setCreateTime(alert.getCreateTime().toString());
                alertData.setHandlerId("system"); // 默认处理人
                alertData.setHandleTime(null); // 处理时间为空

                alertDataList.add(alertData);
            }

            System.out.println("✅ 从数据库加载告警数据: " + alertDataList.size() + " 条");
            return alertDataList;

        } catch (Exception e) {
            System.err.println("❌ 从数据库加载告警数据失败: " + e.getMessage());
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
}
